<template>
	<div id="space-detail-view">
		<!-- 空间信息 -->
		<a-flex justify="space-between" align="center" style="margin-bottom: 16px; padding: 0 70px 0 0px">
			<h2>
				{{ space?.spaceName }} （{{ space?.spaceType !== undefined ? SPACE_TYPE_MAP[space.spaceType] : '未知类型' }}）
			</h2>
			<a-space size="middle">
				<a-button v-if="canUploadPicture" type="primary" :href="`/add_picture?spaceId=${id}`" target="_blank">
					+ 上传图片
				</a-button>
				<a-button
					v-if="canManageSpaceUser"
					type="primary"
					ghost
					:icon="h(TeamOutlined)"
					:href="`/spaceUserManage/${id}`"
					target="_blank"
				>
					成员管理
				</a-button>
				<a-button
					v-if="canManageSpaceUser"
					type="primary"
					ghost
					:icon="h(BarChartOutlined)"
					:href="`/space_analyze?spaceId=${id}`"
					target="_blank"
				>
					空间分析
				</a-button>
				<a-button
					v-if="canEditPicture"
					type="default"
					:icon="h(EditOutlined)"
					@click="openBatchEditModal"
					:disabled="currentPagePictureIds.length === 0"
				>
					批量编辑
				</a-button>
				<a-button v-if="canManageSpaceUser" type="default" danger :icon="h(DeleteOutlined)" @click="doDeleteSpace">
					删除空间
				</a-button>
				<a-tooltip :title="`占用空间：${formatSize(space?.totalSize)} / ${formatSize(space?.maxSize)}`">
					<a-progress type="circle" :size="42" :percent="spaceUsagePercent" />
				</a-tooltip>
			</a-space>
		</a-flex>

		<!-- 搜索表单 -->
		<PictureSearchForm
			:show-review-status="false"
			:init-search-params="initSearchParams"
			@search="onSearch"
			@reset="onSearch"
		/>
		<!-- 按颜色搜索，跟其他搜索条件独立 -->
		<a-form-item label="按颜色搜索">
			<ColorPicker format="hex" @pureColorChange="onColorChange" />
		</a-form-item>

		<!-- 图片列表 -->
		<PictureList
			:dataList="dataList"
			:loading="loading"
			:showOperations="true"
			:onReload="fetchData"
			:canDelete="canDeletePicture"
			:canEdit="canEditPicture"
			:showPagination="true"
			:total="total"
			:current="searchParams.current"
			:pageSize="searchParams.pageSize"
			:onPageChange="onPageChange"
		/>
		<BatchEditPictureModal
			ref="batchEditModalRef"
			:pictureIdList="currentPagePictureIds"
			:spaceId="props.id as number"
			@success="onBatchEditSuccess"
		/>
	</div>
</template>

<script setup lang="ts">
import { listPictureVoByPageUsingPost, searchPictureByColorUsingPost } from '@/api/pictureController'
import { getSpaceVoByIdUsingGet, deleteSpaceUsingPost } from '@/api/spaceController'
import { formatSize } from '@/utils'
import { message, Modal } from 'ant-design-vue'
import { onMounted, reactive, ref, computed, h, watchEffect, watch } from 'vue'
import PictureList from '@/components/picture/PictureList.vue'
import PictureSearchForm from '@/components/picture/PictureSearchForm.vue'
import { useRouter } from 'vue-router'
import { ColorPicker } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'
import BatchEditPictureModal from '@/components/modal/BatchEditPictureModal.vue'
import DeleteSpaceConfirm from '@/components/modal/DeleteSpaceConfirmModal.vue'
import { EditOutlined, BarChartOutlined, DeleteOutlined, TeamOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue'
import { SPACE_PERMISSION_ENUM, SPACE_TYPE_MAP } from '@/constants/space'

interface Props {
	id: string | number
}

const props = defineProps<Props>()
const space = ref<API.SpaceVO>()
const selectedColor = ref('#ff0000') // 默认红色

// 通用权限检查函数
function createPermissionChecker(permission: string) {
	return computed(() => {
		return (space.value?.permissionList ?? []).includes(permission)
	})
}

// 定义权限检查
const canManageSpaceUser = createPermissionChecker(SPACE_PERMISSION_ENUM.SPACE_USER_MANAGE)
const canUploadPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_UPLOAD)
const canEditPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDeletePicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)

// 计算空间使用百分比
const spaceUsagePercent = computed(() => {
	if (!space.value?.totalSize || !space.value?.maxSize) {
		return 0
	}
	return Math.round((space.value.totalSize / space.value.maxSize) * 100)
})

const route = useRouter()

// 获取空间数据
const fetchSpaceDetail = async () => {
	// 获取展示用的空间信息
	const res = await getSpaceVoByIdUsingGet({ id: props.id as any })
	if (res.data.code === 0 && res.data.data) {
		space.value = res.data.data
	} else {
		message.error('获取空间详情失败：' + res.data.message)
		route.push('/')
		return
	}
}

onMounted(() => {
	// 页面加载时获取数据
	fetchSpaceDetail()
	fetchData()
})

//  图片表单数据
const dataList = ref<API.PictureVO[]>([])
const total = ref(0)
const loading = ref(false)

// 批量编辑模态框引用
const batchEditModalRef = ref()

// 计算当前页图片 ID 列表
const currentPagePictureIds = computed(() => {
	return dataList.value.map((picture) => picture.id).filter((id): id is number => id !== undefined)
})

// 计算属性：搜索表单的初始参数
const initSearchParams = computed(() => ({
	spaceId: props.id,
}))

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
	current: 1,
	pageSize: 10,
	sortField: 'createTime',
	sortOrder: 'descend', // 修正为降序，最新图片在前
	spaceId: props.id as any, // 查询指定空间的图片
})

// 处理搜索事件
const onSearch = (newSearchParams: any) => {
	// 直接更新搜索参数，不做任何转换
	Object.assign(searchParams, newSearchParams)
	// 重新获取数据
	fetchData()
}

// 获取数据
const fetchData = async () => {
	loading.value = true
	try {
		const res = await listPictureVoByPageUsingPost(searchParams as any)
		if (res.data.code === 0 && res.data.data) {
			dataList.value = res.data.data.records ?? []
			total.value = res.data.data.total || 0
		} else {
			message.error('获取图片列表失败：' + res.data.message)
			route.push('/')
			return
		}
		// console.log('获取图片列表成功', dataList.value)
	} catch (error) {
		message.error('获取图片列表失败，请重试')
	} finally {
		loading.value = false
	}
}

// 重置当前页为1
const onPageChange = (page: number, pageSize: number) => {
	searchParams.current = page
	searchParams.pageSize = pageSize
	fetchData()
}

// 处理颜色选择变化
const onColorChange = async (color: string) => {
	selectedColor.value = color // 更新选中颜色
	loading.value = true
	try {
		const res = await searchPictureByColorUsingPost({
			picColor: color,
			spaceId: props.id as any,
		})
		if (res.data.code === 0 && res.data.data) {
			const data = res.data.data ?? []
			dataList.value = data
			total.value = data.length
		} else {
			message.error('按颜色搜索失败：' + res.data.message)
		}
	} catch (error) {
		message.error('按颜色搜索失败，请重试')
	} finally {
		loading.value = false
	}
}

// 批量编辑成功回调
const onBatchEditSuccess = () => {
	// 重新获取数据
	fetchData()
}

// 打开批量编辑模态框
const openBatchEditModal = () => {
	if (batchEditModalRef.value) {
		batchEditModalRef.value.openModal()
	}
}

// 删除空间
const doDeleteSpace = async () => {
	const spaceId = props.id
	if (!spaceId) {
		message.error('空间ID不存在')
		return
	}

	Modal.confirm({
		title: '⚠️ 危险操作确认',
		icon: createVNode(DeleteOutlined),
		content: () =>
			h(DeleteSpaceConfirm, {
				spaceName: space.value?.spaceName,
				pictureCount: dataList.value.length,
				spaceSize: formatSize(space.value?.totalSize),
			}),
		okText: '确认删除',
		okType: 'danger',
		cancelText: '取消',
		width: 500,
		async onOk() {
			try {
				const res = await deleteSpaceUsingPost({ id: spaceId as any })
				if (res.data.code === 0) {
					message.success('删除空间成功')
					route.push('/my_space')
				} else {
					message.error('删除空间失败：' + res.data.message)
				}
			} catch (error: any) {
				message.error('删除空间失败：' + error.message)
			}
		},
	})
}

// 监听空间 ID 变化,空间 ID 变化则需要重新加载数据
watch(
	() => props.id,
	(newSpaceId) => {
		// 更新搜索参数中的空间 ID
		searchParams.spaceId = newSpaceId as any
		// 重置页码为第一页
		searchParams.current = 1
		// 重新获取空间详情和图片数据
		fetchSpaceDetail()
		fetchData()
	}
)
</script>

<style scoped lang="scss">
#space-detail-view {
	padding: 16px 0;
}
</style>
